package umlTool;

import java.io.File;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.*;

/**
 * represents a project
 * 
 * @author Mimo
 * 
 */
public class Project {
	private String name;
	Vector<ClassDiagram> classes;
	Vector<relationDiagram> relations;

	public Project() {
		classes = new Vector<ClassDiagram>();
		relations = new Vector<relationDiagram>();
	}

	public Project(String name) {
		this();
		this.name = name;
	}

	Project(File file) {
		this();
		try {
			DocumentBuilderFactory docFac = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder docBuilder = docFac.newDocumentBuilder();
			Document doc = docBuilder.parse(file);
			doc.getDocumentElement().normalize();
			System.out.println(doc.getDocumentElement().getAttribute("name"));
			this.name = doc.getDocumentElement().getAttribute("name");
			NodeList classes = doc.getElementsByTagName("classDiagram");
			for (int i = 0; i < classes.getLength(); i++) {
				this.classes.add(new ClassDiagram((Element) classes.item(i)));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addClass(ClassDiagram diag) {
		classes.add(diag);
	}

	public void save(String path) {
		try {
			DocumentBuilderFactory f = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = f.newDocumentBuilder();
			Document d = db.newDocument();
			Element project = d.createElement("Project");
			project.setAttribute("name", name);
			d.appendChild(project);
			for (ClassDiagram diag : classes) {
				project.appendChild(diag.saveToXml(d));
			}
			for (relationDiagram rel : relations) {
				project.appendChild(rel.saveToXml(d));
			}
			TransformerFactory transformerFactory = TransformerFactory
					.newInstance();
			Transformer transformer = transformerFactory.newTransformer();
			DOMSource source = new DOMSource(d);
			StreamResult result = new StreamResult(new File(path));
			transformer.transform(source, result);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	void setName(String name) {
		this.name = name;
	}

	String getName() {
		return name;
	}

	/**
	 * generate code
	 * 
	 * @param path path of folder
	 */
	public void generateCode(String path) {
		for (ClassDiagram d : classes) {
			d.saveToFile(path + "\\" + d.getName() + ".JAVA");
		}
	}
}
